package com.woniuxy.service.impl;

import com.woniuxy.entity.UserAddress;
import com.woniuxy.mapper.AddressMapper;
import com.woniuxy.service.AddressService;
import com.woniuxy.util.UserContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Resource
    private AddressMapper addressMapper;

    public List<UserAddress> queryAddressByUserId() throws ParseException {
        Integer userId = UserContext.getUserId();
        List<UserAddress> userAddressList = addressMapper.queryAddressByUserId(userId);
        return userAddressList;
    }

    public void addAddress(UserAddress userAddress) throws ParseException {
        Integer userId = UserContext.getUserId();
        userAddress.setUserId(userId);
        addressMapper.addAddress(userAddress);
    }

    public void updateAddress(UserAddress userAddress) throws ParseException {
        Integer userId = UserContext.getUserId();
        userAddress.setUserId(userId);
        addressMapper.updateAddress(userAddress);
    }

    public void deleteAddress(Integer id) {
        addressMapper.deleteAddress(id);
    }

    public void changeDefaultAddress(Integer id) throws ParseException {
        Integer userId = UserContext.getUserId();
        List<UserAddress> userAddressList = addressMapper.queryAddressByUserId(userId);
        for (UserAddress userAddress : userAddressList) {
            if (userAddress.getDefaultAddress() == 1) {
                userAddress.setDefaultAddress(0);
            }
        }
        for (UserAddress userAddress : userAddressList) {
            if (userAddress.getId().equals(id)) {
                userAddress.setDefaultAddress(1);
            }
        }
        for (UserAddress userAddress : userAddressList) {
            if(!userAddress.getId().equals(2)){
                addressMapper.changeDefaultAddress(userAddress);
            }
        }
    }

    public UserAddress queryAddressById(Integer id) {
        UserAddress userAddress = addressMapper.queryAddressById(id);
        return userAddress;
    }
}
